package com.lzh.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lzh.common.to.mq.SeckillOrderTo;
import com.lzh.common.utils.R;
import com.lzh.common.vo.MemberResponseVo;
import com.lzh.gulimall.seckill.feign.CouponFeignService;
import com.lzh.gulimall.seckill.feign.ProductFeignService;
import com.lzh.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.lzh.gulimall.seckill.service.SeckillService;
import com.lzh.gulimall.seckill.to.SeckillSkuRedisTo;
import com.lzh.gulimall.seckill.vo.SeckillSessionWithSkusVo;
import com.lzh.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @ClassName SeckillServiceImpl
 * @Description TODO
 * @Author liuzhihui
 * @Date 2020/9/9 18:43
 * @Version 1.0
 **/
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";

    private final String SECKILL_CHARE_PREFIX = "seckill:skus";
    //+商品随机码
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    /**
     * 通过定时任务，上架最近三天参与秒杀的商品
     */
    @Override
    public void uploadSeckillSkuLatest3Days() {
        //获取最近三天参与秒杀的商品
        R session = couponFeignService.getLates3DaySession();

        if (session.getCode()==0){
            //上架商品
            List<SeckillSessionWithSkusVo> sessionData = (List<SeckillSessionWithSkusVo>) session.getData("data", new TypeReference<List<SeckillSessionWithSkusVo>>() {});
            //缓存到Redis
            //1、缓存活动信息
            saveSessionInfos(sessionData);

            //2、缓存活动的关联商品信息
            saveSessionSkuInfo(sessionData);
        }
    }
    /**
     * 缓存秒杀活动信息
     * @param sessions
     */
    private void saveSessionInfos(List<SeckillSessionWithSkusVo> sessions) {
        if (sessions!=null){
            sessions.stream().forEach(session -> {

                //获取当前活动的开始和结束时间的时间戳
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();

                //存入到Redis中的key
                String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;

                //判断Redis中是否有该商品信息，如果没有才进行添加
                Boolean hasKey = redisTemplate.hasKey(key);
                //没有
                if (!hasKey) {
                    //获取到活动中所有商品的skuId
                    List<String> skuIds = session.getRelationSkus().stream()
                            .map(item -> item.getPromotionSessionId() + "-" + item.getSkuId().toString()).collect(Collectors.toList());
                    //[seckill:sessions:startTime_endTime,[1,场次id-商品id]]
                    redisTemplate.opsForList().leftPushAll(key,skuIds);
                }
            });
        }
    }
    /**
     * 缓存秒杀活动所关联的商品信息
     * @param sessions
     */
    private void saveSessionSkuInfo(List<SeckillSessionWithSkusVo> sessions) {
        if (sessions!=null){
            sessions.stream().forEach(session -> {
                //准备hash操作，绑定hash
                BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
                session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                    //生成随机码
                    String token = UUID.randomUUID().toString().replace("-", "");
                    String redisKey = seckillSkuVo.getPromotionSessionId().toString() + "-" + seckillSkuVo.getSkuId().toString();
                    //在缓存里不在的商品，保证幂等性
                    if (!operations.hasKey(redisKey)) {
                        //缓存我们商品信息
                        SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                        Long skuId = seckillSkuVo.getSkuId();
                        //1、先查询sku的基本信息，调用远程服务
                        R info = productFeignService.getSkuInfo(skuId);
                        if (info.getCode() == 0) {
                            SkuInfoVo skuInfo = (SkuInfoVo) info.getData("skuInfo",new TypeReference<SkuInfoVo>(){});
                            redisTo.setSkuInfo(skuInfo);
                        }

                        //2、sku的秒杀信息
                        BeanUtils.copyProperties(seckillSkuVo,redisTo);

                        //3、设置当前商品的秒杀时间信息
                        redisTo.setStartTime(session.getStartTime().getTime());
                        redisTo.setEndTime(session.getEndTime().getTime());

                        //4、设置商品的随机码（防止恶意攻击）
                        redisTo.setRandomCode(token);

                        //序列化json格式存入Redis中
                        String seckillValue = JSON.toJSONString(redisTo);
                        //seckillSkuVo.getPromotionSessionId()活动场次id
                        operations.put(seckillSkuVo.getPromotionSessionId().toString() + "-" + seckillSkuVo.getSkuId().toString(),seckillValue);

                        //并发控制，限流
                        //如果当前这个场次的商品库存信息已经上架就不需要上架
                        //5、使用库存作为分布式Redisson信号量（限流）
                        // 使用库存作为分布式信号量
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                        // 商品可以秒杀的数量作为信号量
                        semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                    }
                });
            });
        }
    }

    //返回当前时间可以参与的秒杀商品信息
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        try (Entry entry = SphU.entry("seckillSkus")) {
            //1、确定当前属于哪个秒杀场次
            long currentTime = System.currentTimeMillis();

            //从Redis中查询到所有key以seckill:sessions开头的所有数据
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            for (String key : keys) {
                //seckill:sessions:1594396764000_1594453242000
                String replace = key.replace(SESSION_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                //获取存入Redis商品的开始时间
                long startTime = Long.parseLong(s[0]);
                //获取存入Redis商品的结束时间
                long endTime = Long.parseLong(s[1]);

                //判断是否是当前秒杀场次
                if (currentTime >= startTime && currentTime <= endTime) {
                    //2、获取这个秒杀场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hasOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
                    assert range != null;
                    List<String> listValue = hasOps.multiGet(range);
                    if (listValue != null && listValue.size() >= 0) {
                        List<SeckillSkuRedisTo> collect = listValue.stream().map(item -> {
                            String items = (String) item;
                            SeckillSkuRedisTo redisTo = JSON.parseObject(items, SeckillSkuRedisTo.class);
                            //当前秒杀开始需要随机码
//                             redisTo.setRandomCode(null);
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流{}",e.getMessage());
        }
        return null;
    }

    /**
     * 根据skuId查询商品是否参加秒杀活动
     * @param skuId
     * @return
     */
    @Override
    public SeckillSkuRedisTo getSkuSeckilInfo(Long skuId) {

        //1、找到所有需要秒杀的商品的key信息---seckill:skus
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);

        //拿到所有的key，再做正则匹配，而不是再redis上做正则匹配，节省性能
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            //4-45 正则表达式进行匹配
            String reg = "\\d-" + skuId;
            for (String key : keys) {
                //如果匹配上了
                if (Pattern.matches(reg,key)) {
                    //从Redis中取出数据来
                    String redisValue = hashOps.get(key);
                    //进行序列化
                    SeckillSkuRedisTo redisTo = JSON.parseObject(redisValue, SeckillSkuRedisTo.class);

                    //随机码
                    Long currentTime = System.currentTimeMillis();
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    //如果当前时间大于等于秒杀活动开始时间并且要小于活动结束时间
                    if (currentTime >= startTime && currentTime <= endTime) {
                        return redisTo;
                    }
                    redisTo.setRandomCode(null);
                    return redisTo;
                }
            }
        }
        return null;
    }

    /**
     * 秒杀
     *
     * 这里超快，因为这里的所有操作都是在redis里操作，最多有个给mq发消息的操作
     * 假设整个方法花费20ms,一个线程从请求controller进来，到响应，加上网络传
     * 输，假设50ms,那么单线程一秒能容纳20的并发，如果用的tomcat，500个线程，
     * 500*20=10000，那么单个tomcat的在处理秒杀这一块，吞吐量能达到10000
     *
     * 实际测试3毫秒...更厉害了
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        long s1=System.currentTimeMillis();

        //获取当前用户
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        //获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);

        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)){
            return null;
        }else {
            SeckillSkuRedisTo redis = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //校验合法性
            //校验秒杀的商品是否还处于秒杀时间
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long currentTime = System.currentTimeMillis();

            //存到redis里数据的存活时间
            long ttl=endTime-currentTime;

            //秒杀的商品处于秒杀时间
            if (currentTime>=startTime && currentTime<=endTime){
                //校验随机码和商品id
                String randomCode = redis.getRandomCode();
                String skuId = redis.getPromotionSessionId()+"-"+ redis.getSkuId();
                //随机码和商品id,校验
                if (randomCode.equals(key) && skuId.equals(killId)){
                    //校验购物数量是否小于等于限制的数量
                    if(num<=redis.getSeckillLimit()){
                        //校验当前用户是否已经买过了,幂等性。
                        //如果秒杀成功，就去redis占位。
                        // key:userId_SessionId_Skuid
                        //setIfAbsent不存在才能设置
                        String redisKey = memberResponseVo.getId() + "_" + skuId;
                        //自动过期，为秒杀结束,
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MICROSECONDS);
                        //占位成功，当前用户第一次购买
                        if (aBoolean){
                            //获取分布式信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            boolean b = semaphore.tryAcquire(num);
                            if (b){
                                //秒杀成功，快速下单。发送mq消息
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                seckillOrderTo.setOrderSn(timeId);
                                seckillOrderTo.setMemberId(memberResponseVo.getId());
                                seckillOrderTo.setNum(num);
                                seckillOrderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                seckillOrderTo.setSkuId(redis.getSkuId());
                                seckillOrderTo.setSeckillPrice(redis.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrderTo);

                                long s2=System.currentTimeMillis();
                                log.info("耗时："+(s2-s1));
                                return timeId;
                            }else {
                                return null;
                            }
                        }else {
                            //占位失败，当前用户已经购买过
                            return null;
                        }
                    }
                }else {
                    return null;
                }
            }else {
                return null;
            }
        }
        return null;
    }


}
